package cn.kgc;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * @author YC
 */
public class CreateNode implements Watcher {

    /**
     * 倒计时闩锁，初始值为1
     */
    private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);

    public static void main(String[] args) {
        try (ZooKeeper zooKeeper =
                     new ZooKeeper("192.168.8.106:2181", 5000, new CreateNode())) {
            // 等待连接（倒计时闩锁值为0才能连接）
            COUNT_DOWN_LATCH.await();
            // 连接状态为：CONNECTED
            System.out.println(zooKeeper.getState());
            // 创建节点，向节点中保存数据
            // ACL权限：OPEN_ACL_UNSAFE
            // 持久节点：PERSISTENT
            String createNodePath = zooKeeper
                    .create("/kgc-test", "测试添加".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            // 从Zookeeper中获得节点的数据，将数据打印出来
            System.out.println("创建的节点路径：" + createNodePath);
            byte[] data = zooKeeper.getData(createNodePath, null, null);
            System.out.println("节点中的数据：" + new String(data));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 事件通知
     *
     * @param watchedEvent 事件
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        // 客户端监听服务端的连接事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 连接成功则释放倒计时闩锁（值-1）
            COUNT_DOWN_LATCH.countDown();
        }
    }

}
